﻿using System;
using System.IO;
using System.IO.Packaging;
using System.Printing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Threading;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;

namespace WpfPrintDemo
{
    partial class PrintPreviewWin : Window
    {
        private delegate void LoadXpsMethod();

        private readonly object m_data;

        private readonly FlowDocument m_doc;

        /// <summary>
        /// 是否纵向
        /// </summary>
        private readonly bool m_isVertical = true;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="content"></param>
        /// <param name="data"></param>
        /// <param name="renderer"></param>
        /// <param name="isVertical">是否纵向</param>
        public PrintPreviewWin(ContentControl content, object data, IPrintRenderer renderer = null, bool isVertical = true)
        {
            InitializeComponent();
            m_data = data;

            CommandBindings.Add(new CommandBinding(ApplicationCommands.Print, OnPrint));

            m_doc = LoadViewAndData(content, data, renderer);
            Dispatcher.BeginInvoke(new LoadXpsMethod(LoadXps), DispatcherPriority.ApplicationIdle);
        }

        /// <summary>
        /// 加载打印数据
        /// </summary>
        /// <param name="content"></param>
        /// <param name="data"></param>
        /// <param name="renderer"></param>
        /// <param name="isVertical">是否纵向</param>
        /// <returns></returns>
        public static FlowDocument LoadViewAndData(ContentControl content, object data, IPrintRenderer renderer = null, bool isVertical = true)
        {
            FlowDocument doc = content.FindName("PrintFlowDocument") as FlowDocument;

            if (doc == null)
                return doc;

            if (isVertical)
            {
                doc.PageHeight = 1122;
                doc.PageWidth = 794;
            }
            else
            {
                doc.PageWidth = 1122;
                doc.PageHeight = 794;
            }

            doc.PagePadding = new Thickness(50);
            doc.DataContext = data;
            if (renderer != null)
            {
                renderer.LoadData(doc, data);
            }
            return doc;
        }

        /// <summary>
        /// 加载Xps
        /// </summary>
        public void LoadXps()
        {
            //构造一个基于内存的xps document
            MemoryStream ms = new MemoryStream();
            Package package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite);
            Uri DocumentUri = new Uri("pack://InMemoryDocument.xps");
            PackageStore.RemovePackage(DocumentUri);
            PackageStore.AddPackage(DocumentUri, package);
            XpsDocument xpsDocument = new XpsDocument(package, CompressionOption.Fast, DocumentUri.AbsoluteUri);

            //将flow document写入基于内存的xps document中去
            XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
            writer.Write(((IDocumentPaginatorSource)m_doc).DocumentPaginator);

            //获取这个基于内存的xps document的fixed document
            docViewer.Document = xpsDocument.GetFixedDocumentSequence();

            //关闭基于内存的xps document
            xpsDocument.Close();
        }

        /// <summary>
        /// Ctrl+P快捷键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnPrint(object sender, ExecutedRoutedEventArgs e)
        {
            Print();
        }

        /// <summary>
        /// 点击打印按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PrintClick(object sender, RoutedEventArgs e)
        {
            Print();
        }

        /// <summary>
        /// 打印
        /// </summary>
        void Print()
        {
            if (m_doc == null)
                return;
            var tempDocument = (IDocumentPaginatorSource)m_doc;

            if (tempDocument == null)
                return;

            PrintDialog pDialog = new PrintDialog();
            pDialog.PrintTicket.PageOrientation = m_isVertical ? PageOrientation.Portrait : PageOrientation.Landscape;

            if (pDialog.ShowDialog() == true)
            {
                pDialog.PrintDocument(tempDocument.DocumentPaginator, "");
            }
        }
    }
}
